<template>
  <div class="box">
    <div class="search">
      <img src="../../public/img/gaode.png" alt="高德地图">
      <el-input  @focus="handleFocus()" :suffix-icon="Search" v-model="searchValue" placeholder="搜索位置、公交站、地铁站"></el-input>
      <div @click="handlerouter" class="router">
        <img src="../../public/img/router.png" alt="路线规划">
      </div>
    </div>

    <!-- 当获取焦点 并且输入内容为空的时候  展示的内容-->
    <template v-if="isfocus&&searchValue.trim()== ''">
      <div  class="foucs-content">
        <div class="top-content">
          <!-- 美食 -->
          <div @click="getfood()" class="top-one">
            <img src="../../public/img/search_food.png" alt="美食">
            <p>美食</p>
          </div>
          <!-- 酒店 -->
          <div @click="gethotel()" class="top-two">
            <img src="../../public/img/search_hotel.png" alt="酒店">
            <p>酒店</p>
          </div>
          <!-- 景点 -->
          <div @click="getview()" class="top-three">
            <img src="../../public/img/search_view.png" alt="景点">
            <p>景点</p>
          </div>
          <!-- 小区 -->
          <div @click="getcommunity()" class="top-four">
            <img src="../../public/img/search_house.png" alt="小区">
            <p>小区</p>
          </div>
        </div>
     
        <!--json-server 接口数据-->
        <div class="json-data">
             <ul>
                <li v-for="(item,index) in historydata">
                  <i class="iconfont icon-history-data"></i>
                  {{ item.cityname }}
                   <i @click="deleteHistory(item.id,index)" class="iconfont icon-close"></i>
                </li>
             </ul>
        </div>

        <!-- 下面的去下载二维码 -->
        <div class="bottom-content">
          <div class="bottom-left">
            <h2>高德地图手机版</h2>
            <p>高德地图 哪都熟</p>
            <button>去官网下载</button>
          </div>
          <div class="bottom-right">
            <img src="../../public/img/bannerQrcode-1.png" alt="下载二维码">
          </div>
        </div>
      </div>
    </template>

    <!-- 当获取焦点 并且输入内容不为空的时候  展示的内容 -->
    <ul v-show="isShowtips" class="tips" @click="hideTipsContainer">
      <li @click="handleclick(item.names,index)" v-for="(item,index) in tipscity" :key="item.id">
        <i class="iconfont icon-postion"></i> 
        <span v-html="item.name"></span> 
        <span class="district">{{item.district }}</span>
      </li>
    </ul>

    <!-- 推荐列表 -->
    <ul v-show="isrecommendlist" class="recommendlist">
      <li v-for="(item, index) in recommend" :key="index">
        <div class="left">
          <p>{{item.name}}</p>
          <p><i v-for="i in 5" :key="i" class="iconfont icon-Star"></i></p>
          <p>人均:<span>￥999</span></p>
          <p>{{ item.address }}</p>
        </div>
        <div class="right">
          <img :src="recommendimg" alt="推荐图片">
        </div>
      </li>
    </ul>

    <!-- 驾车路线查询 -->
    <div id="my-panel" v-show="isroutershow">
      <!-- 第一行小车的图标 -->
      <div><i class="iconfont icon-car" style="font-size: 30px;color:white;"></i></div>

      <!-- 两个输入框 -->
      <el-input 
        v-model="start" 
        @input="handlestartInput" 
        @focus="handleStartFocus" 
        placeholder="请输入起点"
      >
        <template #prepend>起</template>
      </el-input>
      <el-input  
        v-model="end" 
        @input="handleendtInput" 
        @focus="handleEndFocus" 
        placeholder="请输入终点"
      >
        <template #prepend>终</template>
      </el-input>

      <!-- 最下面一行清除路线和 开车去 -->
      <div class="bottom">
        <div class="clear" @click="clearRoute">清除路线</div>
        <el-button class="drive" @click="calculateRoute">开车去</el-button>
      </div>

      <!-- 互换起始点和终点 -->
      <div class="exchange" @click="swapStartEnd"><i class="iconfont icon-zhihuan"></i></div>
    </div>
  </div>
</template>

<script setup>
// import {gethistoryData} from '@/api' 
import AMapLoader from "@amap/amap-jsapi-loader";
import { Search } from '@element-plus/icons-vue'
import axios from 'axios';
import { ElMessage } from 'element-plus'
import { onMounted, ref, inject, watch } from "vue";

// 注入地图实例
const { Amap, map } = inject('mapandAmap')

// 搜索相关
const searchValue = ref('')
let isfocus = ref(false)
let placeSearch = null
let isShowtips = ref(false)
let recommend = ref([])
let isrecommendlist = ref(false)
let tipscity = ref([])
let recommendimg = ref('')




// 路线规划相关
let isroutershow = ref(false)  // 控制#my-panel显示/隐藏的状态变量
let start = ref('')
let end = ref('')
let isStartFocused = ref(false)  // 起点输入框聚焦状态
let isEndFocused = ref(false)    // 终点输入框聚焦状态
let driving = null               // 驾车路线实例
let routePolyline = null         // 存储路线折线对象，用于单独清除

let pathlnglat = []

let historydata = ref([])

// 监听地图实例和搜索值变化
watch([Amap, map, searchValue], ([AmapInstance, mapInstance, searchVal]) => {
  // 根据焦点状态同步搜索值到对应的输入框
  if (isStartFocused.value) {
    start.value = searchVal
  } else if (isEndFocused.value) {
    end.value = searchVal
  }
if(searchVal.trim()== ''){
    isrecommendlist.value = false
}
  // 处理提示框位置
  const tipsul = document.querySelector('.tips')
  if (tipsul) {
    if (isroutershow.value) {
      tipsul.style.top = '300px'
    } else {
      tipsul.style.top = '110px'
    }
  }

  // 高德地图实例就绪且有搜索值时，执行搜索
  if (AmapInstance && mapInstance && searchVal) {
    const autoOptions = { city: "全国" }
    const autocomplete = new AmapInstance.AutoComplete(autoOptions)
    
    autocomplete.search(searchVal, (status, result) => {
      if (status === 'complete' && result.tips) {
        recommend.value = result.tips.slice(1, 10)
        tipscity.value = result.tips.map(item => ({
          id: item.id,
          names: item.name,
          name: item.name.replace(searchVal, `<span style="color:rgb(56, 156, 234)">${searchVal}</span>`),
          district: item.district
        }))
      }
    })

    // 初始化地点搜索实例
    if (!placeSearch) {
      placeSearch = new AmapInstance.PlaceSearch({
        city: "全国",
        map: mapInstance
      })
    }
  }

  // 控制提示框显示状态
  isShowtips.value = searchVal.trim() !== ''

  // 点击地图关闭所有面板
  if (mapInstance) {
    mapInstance.off('click', handleMapClick)
    mapInstance.on('click', handleMapClick)
  }

// 点击地图收起提示框
  map.value.on('click', function(e){
    isShowtips.value=false
    isfocus.value=false
    isrecommendlist.value=false
    isroutershow.value=false
   
    
  })


  // 初始化驾车路线（仅在实例就绪时）
  if (AmapInstance && mapInstance && !driving) {
    driving = new AmapInstance.Driving({
      policy: AmapInstance.DrivingPolicy.LEAST_TIME,
      map: mapInstance,
      panel: "my-panel"
    })

    // 监听路线绘制完成事件，保存折线对象
    // driving.on('complete', function(result) {
    //   if (result.routes && result.routes[0] && result.routes[0].path) {
    //     // 清除之前的路线
    //     if (routePolyline) {
    //       mapInstance.remove(routePolyline);
    //     }
    //     // 创建新的路线折线
    //     routePolyline = new AmapInstance.Polyline({
    //       path: result.routes[0].path,
    //       strokeColor: "#3366FF",
    //       strokeWeight: 5,
    //       strokeOpacity: 0.8
    //     });
    //     mapInstance.add(routePolyline);
    //   }
    // });

    //  var route = new Amap.DragRoute(map, pathlnglat, 0);
  //查询导航路径并开启拖拽导航
    //  route.search();

  }
})

// function ()

// 地图点击事件处理
function handleMapClick() {
  isShowtips.value = false
  isfocus.value = false
  isrecommendlist.value = false
  isroutershow.value = false
}

async function getHistoryData() {
  const response = await axios.get('http://localhost:3000/city')
  console.log(response.data)
  historydata.value = response.data
}

// 监听全局回车事件
onMounted(async() => {
   getHistoryData()
  const handleKeydown = (e) => {
    if (e.code === 'Enter' && searchValue.value.trim() !== '') {
      handleclick(searchValue.value)
      isShowtips.value = false
      searchValue.value = ''
    }
  }

  document.addEventListener('keydown', handleKeydown)
  
  // 组件卸载时清理事件
  return () => {
    document.removeEventListener('keydown', handleKeydown)
  }
})

// ：隐藏 tips 容器的事件处理函数
function hideTipsContainer() {
  isShowtips.value = false;
}

// 焦点处理函数
function handleFocus() {
  isfocus.value = true
  isShowtips.value = false
}

function handleStartFocus() {
  isStartFocused.value = true
  isEndFocused.value = false
  isfocus.value = true
  isShowtips.value = false
}

// 起点输入事件
function handlestartInput(val) {
  if (isStartFocused.value) {
    searchValue.value = val
  }
}

// 终点输入事件
function handleendtInput(val) {
  if (isEndFocused.value) {
    searchValue.value = val
  }
}

function handleEndFocus() {
  isEndFocused.value = true
  isStartFocused.value = false
  isfocus.value = true
  isShowtips.value = false
}

// 类型搜索处理
function getfood() {
  searchValue.value = '美食'
  isrecommendlist.value = true
  recommendimg.value = '../../public/img/food.webp'
}

function gethotel() {
  searchValue.value = '酒店'
  isrecommendlist.value = true
  isShowtips.value = false
  recommendimg.value = '../../public/img/hotel.jpg'
}

function getview() {
  searchValue.value = '景点'
  isrecommendlist.value = true
  isShowtips.value = false
  recommendimg.value = '../../public/img/view.jpg'
}

function getcommunity() {
  searchValue.value = '小区'
  isrecommendlist.value = true
  isShowtips.value = false
  recommendimg.value = '../../public/img/house.png'
}

// 提示框点击事件
function  handleclick (name,index) {
    axios.post('http://localhost:3000/city',{"cityname":name}).then(response => {
    console.log('添加成功，后端响应：', response.data);
    // 可加 UI 提示，如 ElMessage.success('添加记录成功')
  })

  historydata.value.push({"cityname":name})
 
  if (isStartFocused.value) {
    start.value = name
    isStartFocused.value = false
    placeSearch.search(name,function(status,result){
      if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois[index]) {
        pathlnglat[0] = [result.poiList.pois[index].location.lng, result.poiList.pois[index].location.lat]
      }
    })
  } else if (isEndFocused.value) {
    end.value = name
    isEndFocused.value = false
    placeSearch.search(name,function(status,result){
      if (status === 'complete' && result.poiList && result.poiList.pois && result.poiList.pois[index]) {
        pathlnglat[1] = [result.poiList.pois[index].location.lng, result.poiList.pois[index].location.lat]
      }
    })
  } else if(isfocus.value) {
    searchValue.value = name
    placeSearch.search(name)
    
  }
  
  isShowtips.value = false
}


// 历史记录删除事件
function deleteHistory(id,index) {


  console.log(id)
  axios.delete(`http://localhost:3000/city/${id}`).then(response => {
    console.log('删除成功，后端响应：', response.data);
   
    // 数据回显
    historydata.value.splice(index, 1)
  })
}

// 路线规划相关函数：点击路线规划按钮时切换面板显示状态
function handlerouter() {
  isroutershow.value = !isroutershow.value  // 核心逻辑：切换显示/隐藏
  if (isroutershow.value) {
    isfocus.value = false
    isShowtips.value = false
    isrecommendlist.value = false
  }
}

function swapStartEnd() {
  // 检查数组是否有足够元素再交换
  if (pathlnglat.length >= 2) {
    [pathlnglat[0], pathlnglat[1]] = [pathlnglat[1], pathlnglat[0]]
  }
  [start.value, end.value] = [end.value, start.value]
}

function calculateRoute() {
  if (!start.value || !end.value) {
   alert('请输入起点和终点')
    return
  }
  
  if (pathlnglat.length >= 2) {
    driving.search(pathlnglat[0], pathlnglat[1], (status) => {
      if (status !== 'complete') {
       alert('路线规划失败，请重试')
      }
    })
  }
}

// 清除路线函数：添加隐藏面板的逻辑
function clearRoute() {
  if (driving) {
    // 清除地图上的路线
    driving.clear();
    // 清除保存的折线对象
    // if (routePolyline && map.value) {
    //   map.value.remove(routePolyline);
    //   routePolyline = null;
    // }
  }
  // 隐藏路线面板（核心修改点）
  isroutershow.value = false;
  // 不清除输入框内容，只清除路线坐标
  pathlnglat = [];
}
</script>

<style lang="scss" scoped>
@import 'reset-css';
:deep .amap-lib-driving{
  display: none;
}
:deep .amap-call{
    display: none;
}
.box {
  .heighlight {
    color: red;
  }

  position: relative;

  .search {
    position: fixed;
    top: 40px;
    left: 40px;
    display: flex;

    img {
      position: absolute;
      z-index: 100;
      left: 50px;
      top: 7px;
      width: 50px;
      height: 50px;
    }

    .el-input {
      padding-left: 40px;
      font-size: 20px;
      width: 560px;
      height: 65px;

      :deep .el-input__inner {
        text-indent: 3em;
      }
    }

    .router {
      z-index: 100;
      position: relative;
      left: -0.5%;
      width: 62px;
      height: 65px;
      background-color: rgb(248, 248, 248);
      cursor: pointer;

      img {
        top: 15px;
        left: 17px;
        height: 30px;
        width: 30px;
      }
    }
  }

  .foucs-content {
    position: fixed;
    top: 110px;
    left: 80px;
    width: 570px;
    background-color: rgb(246, 247, 248);

    .top-content {
      border-bottom: 1px dashed #ccc;
      display: flex;
      padding-top: 20px;
      justify-content: space-evenly;
      text-align: center;

       div {
        cursor: pointer;

        img {
          margin-bottom: 10px;
          height: 70px;
        }

        p {
          margin-bottom: 15px;
        }
      }
    }


    .json-data{
        ul{
          margin-left: 20px;
          font-size: 13px;
          color: rgb(129, 129, 129);
           border-bottom: 1px dashed #ccc;

          li{
            line-height: 35px;
            height:35px;

            i{
              margin-right: 10px;
            }
            .icon-close{
              display: none;
              margin-right: 30px;
              float: right;
            }
           
          }
          li:hover{
            background-color: rgb(251, 251, 251);
            .icon-close{
              // font-size: 20px;
              display: block;
            }
          }
        }
    }

    .bottom-content {
      display: flex;
      justify-content: space-evenly;

      .bottom-left {
        text-align: center;

        h2 {
          margin-top: 15px;
          font-size: 24px;
          font-weight: 600;
          color: rgb(45, 114, 254);
        }

        p {
          margin: 10px 0px;
          font-weight: 500;
          color: rgb(129, 129, 129);
        }

        button {
          background-color: rgb(26, 105, 255);
          height: 45px;
          width: 150px;
          border-radius: 30px;
          font-size: 17px;
          font-weight: 600;
          color: white;
          border: none;
          cursor: pointer;
        }
      }

      .bottom-right {
        img {
          width: 130px;
          margin-top: 10px;
        }
      }
    }
  }

  .tips {
    position: fixed;
    top: 110px;
    left: 80px;
    width: 570px;
    cursor: pointer;
    background: white;
    z-index: 99;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin: 0;
    padding: 0;

    li {
      text-indent: 1em;
      height: 50px;
      line-height: 50px;
      list-style: none;
      border-bottom: 1px solid #f5f5f5;

      i {
        font-size: 25px;
        margin-right: 10px;
      }

      .district {
        margin-left: 25px;
        color: rgb(195, 195, 195);
      }
    }
  }

  .recommendlist {
    padding: 0;
    position: fixed;
    left: 80px;
    top: 110px;
    width: 570px;
    max-height: 850px;
    overflow-y: auto;
    background: white;
    z-index: 99;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    li {
      display: flex;
      background-color: rgb(255, 255, 255);
      border-bottom: 1px solid #eee;
      list-style: none;

      .left {
        padding: 10px 0px;
        width: 70%;
        margin-left: 30px;

        p:nth-child(1) {
          font-size: 17px;
          color: rgb(86, 86, 86);
          font-weight: 600;
        }

        p:nth-child(2) {
          margin: 5px 0px;

          i {
            margin: 0 2px;
            color: red;
          }
        }

        p:nth-child(3) {
          margin: 5px 0px;
          font-size: 15px;
          color: rgb(86, 86, 86);

          span {
            color: red;
          }
        }

        p:nth-child(4) {
          font-size: 15px;
          color: rgb(86, 86, 86);
        }
      }

      .right {
        width: 30%;

        img {
          margin-top: 15px;
          height: 100px;
          width: 120px;
          object-fit: cover;
        }
      }
    }
  }

  #my-panel {
    position: fixed;
    text-align: center;
    padding-top: 15px;
    top: 40px;
    left: 80px;
    width: 570px;
    height: 250px;
    background-color: rgb(61, 147, 253);
    z-index: 1000;
    border-radius: 4px;

    .el-input {
      margin-top: 20px;
      width: 80%;
      height: 40px;

      :deep .el-input-group__prepend {
        width: 30px;
        background-color: rgb(255, 255, 255);
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .exchange {
      position: absolute;
      top: 100px;
      left: 10px;
     
      cursor: pointer;

      i {
        font-size: 30px;
        color: white;
        font-weight: 600;
      }
    }

    .bottom {
      display: flex;
      justify-content: space-around;
      margin-top: 30px;

      .clear {
        color: white;
        font-size: 15px;
        font-weight: 600;
        cursor: pointer;
        line-height: 35px;
      }

      .drive {
        width: 90px;
        height: 35px;
        background-color: rgb(85, 159, 251);
        border: 0px;
        color: white;
      }
    }
  }
}
</style>
